const router = require('koa-router')()
const svgCaptcha = require('svg-captcha')
const fs = require('fs')
const {join} = require('path')
const formidable = require('formidable')
const jwt = require('jsonwebtoken')
const {adminLogin} = require('../model/login')
const {uploadImgs,getImgList,delImgById} = require('../model/images')
const {getLogisticsList,addLogistics,editLogistics,delLogisticsById,changeTop,searchWord} = require('../model/logistics')
const {getUserList,addUsers,editUsers,delUsersById} = require('../model/users')

const mykey = 'fdskjfoiernknziure8'

router.get('/getConfirm', async(ctx,next) => {
  const confirmImg = svgCaptcha.create();
  ctx.session.captchaText = confirmImg.text

  ctx.body = {'code':200,'data':confirmImg}
})

router.post('/login', async(ctx,next) => {
  const username = ctx.request.body.username;
  const password = ctx.request.body.password;
  const confirm = ctx.request.body.confirm;
  const captchaText = ctx.session.captchaText;

  let res = await adminLogin(username,password);

  if(captchaText !== confirm) {
    return ctx.body = {'code':500,'msg':'验证码错误！'}
  }

  if(res === 'false1') {
    return ctx.body = {'code':500,'msg':'账号不存在！'}
  }

  if(res === 'false2') {
    return ctx.body = {'code':500,'msg':'密码错误！'}
  }

  if(res === true) {
    let token = jwt.sign({'username':username,'password':password},mykey)
    return ctx.body = {'code':200,'msg':'登录成功！',token};
  }
})

router.post('/upload', async(ctx, next) => {
  let authorization = ctx.req.headers.authorization
  let decoded = jwt.verify(authorization,mykey)
  let res = await adminLogin(decoded.username,decoded.password);

  if(res === true) {
    const form = formidable({multiples:true,uploadDir:'public/images',keepExtensions:true});

    form.parse(ctx.req, async(err, fields, files) => {
      if(err) {
        ctx.body = {'code':500,'msg':err}
      }

      uploadImgs(files.file.newFilename.split('.')[0],files.file.newFilename,getfilesize(files.file.size),files.file.mimetype)

      ctx.body = {'code':200,'msg':'成功'}
    })
  }else{
    ctx.body = {'code':500,'msg':'token已到期！请重新获取token！'}
  }
})

router.get('/getImageList', async(ctx, next) => {
  const page = ctx.request.query.page

  let authorization = ctx.req.headers.authorization
  let decoded = jwt.verify(authorization,mykey)
  let res = await adminLogin(decoded.username,decoded.password);

  if(res === true) {
    let result = await getImgList(page)

    result.data.map(item => {
      return item.image = `http://localhost:3001/images/${item.image}`
    })

    ctx.body = {'code':200,'mgs':'成功',totalPages:result.total,data:result.data}
    }else{
    ctx.body = {'code':500,'msg':'token已到期！请重新获取token！'}
  }
})

router.post('/delImage', async(ctx, next) => {
  const id = ctx.request.body.id

  let authorization = ctx.req.headers.authorization
  let decoded = jwt.verify(authorization,mykey)
  let res = await adminLogin(decoded.username,decoded.password);

  if(res === true) {
    let result = await delImgById(id)

    fs.rmSync(join(__dirname,'../public/images',result[0][0].image),{},(err) => {
      if(err) {
        ctx.body = {'code':500,'msg':'失败'}
      }
    })
    ctx.body = {'code':200,'msg':'成功'}
  }else{
    ctx.body = {'code':500,'msg':'token已到期！请重新获取token！'}
  }
})

router.get('/getLogistics', async(ctx, next) => {
  const page = ctx.request.query.page

  let authorization = ctx.req.headers.authorization
  let decoded = jwt.verify(authorization,mykey)
  let res = await adminLogin(decoded.username,decoded.password);

  if(res === true) {
    let result = await getLogisticsList(page)

    ctx.body = {'code':200,'msg':'ok','data':result.data,'totalPages':result.total}
  }else{
    ctx.body = {'code':500,'msg':'token已到期！请重新获取token！'}
  }
})

router.post('/addLogistics', async(ctx, next) => {
  const newLogistic = ctx.request.body.newLogistic;

  let authorization = ctx.req.headers.authorization
  let decoded = jwt.verify(authorization,mykey)
  let res = await adminLogin(decoded.username,decoded.password);

  if(res === true) {
    await addLogistics(newLogistic.name,newLogistic.pathway,newLogistic.address,newLogistic.telephone)

    ctx.body = {'code':200,'msg':'ok'}
  }else{
    ctx.body = {'code':500,'msg':'token已到期！请重新获取token！'}
  }
})

router.post('/editLogistics', async(ctx, next) => {
  const edited = ctx.request.body.edited;

  let authorization = ctx.req.headers.authorization
  let decoded = jwt.verify(authorization,mykey)
  let res = await adminLogin(decoded.username,decoded.password);

  if(res === true) {
    await editLogistics(edited.name,edited.pathway,edited.address,edited.telephone,edited.id)

    ctx.body = {'code':200,'msg':'ok'}
  }else{
    ctx.body = {'code':500,'msg':'token已到期！请重新获取token！'}
  }
})

router.post('/delLogistics', async(ctx, next) => {
  const id = ctx.request.body.id;

  let authorization = ctx.req.headers.authorization
  let decoded = jwt.verify(authorization,mykey)
  let res = await adminLogin(decoded.username,decoded.password);

  if(res === true) {
    await delLogisticsById(id)

    ctx.body = {'code':200,'msg':'ok'}
  }else{
    ctx.body = {'code':500,'msg':'token已到期！请重新获取token！'}
  }
})

router.post('/changeTop', async(ctx, next) => {
  const id = ctx.request.body.id;
  const top = ctx.request.body.top;

  let authorization = ctx.req.headers.authorization
  let decoded = jwt.verify(authorization,mykey)
  let res = await adminLogin(decoded.username,decoded.password);

  if(res === true) {
    await changeTop(id,top)

    ctx.body = {'code':200,'msg':'ok'}
  }else{
    ctx.body = {'code':500,'msg':'token已到期！请重新获取token！'}
  }
})

router.get('/search', async(ctx, next) => {
  const search = ctx.request.query.search

  let authorization = ctx.req.headers.authorization
  let decoded = jwt.verify(authorization,mykey)
  let res = await adminLogin(decoded.username,decoded.password);

  if(res === true) {
    let result = await searchWord(search)

    ctx.body = {'code':200,'msg':'ok','data':result,'totalPages':result.length}
  }else{
    ctx.body = {'code':500,'msg':'token已到期！请重新获取token！'}
  }  
})

function getfilesize(size) {
  if (!size)  return "";
  var num = 1024.00; 
  if (size < num)
      return size + "B";
  if (size < Math.pow(num, 2))
      return (size / num).toFixed(2) + "KB"; 
  if (size < Math.pow(num, 3))
      return (size / Math.pow(num, 2)).toFixed(2) + "MB"; 
}

router.get('/userList', async (ctx, next) => {
  const page = ctx.request.query.page

  let authorization = ctx.req.headers.authorization
  let decoded = jwt.verify(authorization,mykey)
  let res = await adminLogin(decoded.username,decoded.password);

  if(res === true) {
    let result = await getUserList(page)

    ctx.body = {'code':200,'msg':'ok','data':result.data,'totalPages':result.total}
  }else{
    ctx.body = {'code':500,'msg':'token已到期！请重新获取token！'}
  }
})

router.post('/addUser', async (ctx, next) => {
  const newUser = ctx.request.body.newUser;

  let authorization = ctx.req.headers.authorization
  let decoded = jwt.verify(authorization,mykey)
  let res = await adminLogin(decoded.username,decoded.password);

  if(res === true) {
    await addUsers(newUser.name,newUser.telephone,newUser.email,newUser.address)

    ctx.body = {'code':200,'msg':'ok'}
  }else{
    ctx.body = {'code':500,'msg':'token已到期！请重新获取token！'}
  }
})

router.post('/editUser', async (ctx, next) => {
  const edited = ctx.request.body.edited;

  let authorization = ctx.req.headers.authorization
  let decoded = jwt.verify(authorization,mykey)
  let res = await adminLogin(decoded.username,decoded.password);

  if(res === true) {
    await editUsers(edited.name,edited.telephone,edited.email,edited.address,edited.id)
  
    ctx.body = {'code':200,'msg':'ok'}
  }else{
    ctx.body = {'code':500,'msg':'token已到期！请重新获取token！'}
  }
})

router.post('/delUser', async (ctx, next) => {
  const id = ctx.request.body.id;

  let authorization = ctx.req.headers.authorization
  let decoded = jwt.verify(authorization,mykey)
  let res = await adminLogin(decoded.username,decoded.password);

  if(res === true) {
    await delUsersById(id)

    ctx.body = {'code':200,'msg':'ok'}
  }else{
    ctx.body = {'code':500,'msg':'token已到期！请重新获取token！'}
  }
})

module.exports = router
